<template>
  <div class="common_width dm_settlementPage">
    <TableTitle title="结算页">
      <div>
        （当前共有 <i>{{ getTotalNum }}</i> 件商品正在结算）
      </div>
    </TableTitle>
    <el-table
      :data="tableData"
      max-height="386"
      border
      style="width: 100%"
      row-key="id"
      size="small"
    >
      <el-table-column
        v-for="c in columns"
        :key="c.id"
        :prop="c.prop"
        :label="c.label"
        :width="c.width"
        align="center"
      >
        <template slot-scope="scope">
          <img
            v-if="c.prop == 'mainPicture'"
            class="imgs_style"
            :src="scope.row.productPic"
          />
          <router-link
            v-if="c.prop == 'description'"
            class="title_style"
            :to="{ name: 'detail', query: { id: scope.row.productId } }"
          >
            <span :title="scope.row.productSubTitle">{{
              scope.row.productName + " | " + scope.row.productSubTitle
            }}</span>
            <span class="ellipsis">规格：{{ scope.row.productAttr }}</span>
          </router-link>
          <span v-if="c.prop == 'price' || c.prop == 'totalprice'"
            >￥{{
              c.prop == "price"
                ? scope.row["price"]
                : c.prop == "totalprice"
                ? parseFloat(scope.row["price"]) * scope.row["quantity"]
                : 0 | keepTwoDecimalPlaces
            }}</span
          >
          <span v-if="c.prop == 'num'">x{{ scope.row.quantity }}</span>
        </template>
      </el-table-column>
    </el-table>
    <el-row class="dm_settlementPage__pay">
      <el-col :span="24">
        <div class="dm_settlementPage__pay--name">
          <i>更换收货人：</i>
          <el-select placeholder="请选择" size="mini" v-model="checkedName">
            <el-option
              v-for="item in getName"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </div>
        <div>
          <i>收货人：</i>
          <span>{{ getNewAddressObj[0] || "-" }}</span>
        </div>
        <div>
          <i>收货地址：</i>
          <span>{{ getNewAddressObj[2] || "-" }}</span>
        </div>
        <div>
          <i>联系电话：</i>
          <span>{{ getNewAddressObj[1] || "-" }}</span>
        </div>
        <div class="dm_settlementPage__pay--price">
          <i>总金额：</i>
          <span>￥{{ getTotalPrice | keepTwoDecimalPlaces }}</span>
        </div>
        <div class="dm_settlementPage__pay--price">
          <i>应付金额：</i>
          <span>￥{{ getTotalPrice | keepTwoDecimalPlaces }}</span>
        </div>
        <div class="dm_settlementPage__pay--submit">
          <el-button type="primary" round @click="handleSubmitOrders"
            >提交订单</el-button
          >
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import tableTitle from "@/components/tableTitle/index.vue";
import { postSettlementData, postAddOrderData } from "@/api/settlementPage";
import { getNative } from "@/api/weixinPay";
import { formatSpecs } from "@/utils/format";
export default {
  data() {
    return {
      columns: [
        { id: 1, prop: "mainPicture", label: "图片", width: 86 },
        { id: 2, prop: "description", label: "商品" },
        { id: 3, prop: "price", label: "单价", width: 136 },
        { id: 4, prop: "num", label: "数量", width: 119 },
        { id: 5, prop: "totalprice", label: "小计", width: 136 }
      ],
      tableData: [],
      address: [],
      checkedName: "",
      reqParams: {
        cartIds: [],
        memberReceiveAddressId: null,
        payType: 0
        // num: 1,
        // nums: "",
        // totalprice: 0
      }
    };
  },
  mounted() {
    try {
      const { ids } = this.$route.query || {};
      console.log(typeof ids);
      if (typeof ids === 'string'|| typeof ids === 'number') {
        this.postSettlementData([ids]);
      } else {
        this.postSettlementData(ids);
      }
    } catch (error) {
      console.log(error);
    }
  },
  methods: {
    // 提交订单 - 操作
    handleSubmitOrders() {
      let arr =
        this.getName.filter(item => item.value == this.checkedName) || [];
      const { id } = arr[0] || {};
      this.reqParams["memberReceiveAddressId"] = id;
      this.postAddOrderData({
        ...this.reqParams
      });
    },
    // 查询收货地址、商品详情
    async postSettlementData(ids = []) {
      const res = await postSettlementData(ids);
      try {
        if (res.code === 200) {
          const { memberReceiveAddressList = [], cartPromotionItemList = [] } =
            res.data || {};
          const productsInfo = cartPromotionItemList;
          const address = memberReceiveAddressList;
          productsInfo.forEach(item => {
            item.productAttr = formatSpecs(item.productAttr);
          });
          this.tableData = productsInfo;
          this.address = address;

          // 获取 - 默认收货人
          let data = address.filter(item => item.defaultStatus == 1) || [];
          if (data.length) {
            const { name, phoneNumber, province, city, region, detailAddress } =
              data[0] || {};
            this.checkedName = `${name} / ${phoneNumber} / ${province} ${city} ${region} ${detailAddress}`;
          }

          this.reqParams["cartIds"] = productsInfo.map(item => item.id);
          //   this.reqParams["num"] = productsInfo.reduce(
          //     (total, item, index, arr) => total + item.quantity,
          //     0
          //   );
          //   this.reqParams["nums"] = productsInfo
          //     .map(item => item.quantity)
          //     .toString();
          //   this.reqParams["totalprice"] = productsInfo.reduce(
          //     (total, item, index, arr) => total + item.price * item.quantity,
          //     0
          //   );
        }
      } catch (err) {
        console.log(err);
      }
    },
    // 提交订单
    async postAddOrderData(params = {}) {
      const res = await postAddOrderData(params);
      try {
        if (res.code === 200) {
          const { order } = res.data || {};
          const data = {
            outtradeno: order.orderSn,
            totalfee: order.totalAmount,
            orderId: order.id,
            payType: "2"
          };
          if (data) {
            //发起第三方服务-微信支付
            getNative(data).then(res => {
              if (res.code === 200) {
                this.$router.replace({
                  name: "orderDetails",
                  query: {
                    codeUrl: res.data.code_url,
                    orderId: order.id,
                    orderSn: order.orderSn
                  }
                });
              }
            });
          }
        }
      } catch (err) {
        console.log(err);
      }
    }
  },
  computed: {
    getName() {
      let address = this.address;
      let data = address.map(item => {
        return {
          id: item.id,
          label: `${item.name} / ${item.phoneNumber} / ${item.province} ${item.city} ${item.region} ${item.detailAddress}`,
          value: `${item.name} / ${item.phoneNumber} / ${item.province} ${item.city} ${item.region} ${item.detailAddress}`
        };
      });
      return data;
    },
    getNewAddressObj() {
      let checkedName = this.checkedName;
      return checkedName.split(" / ") || [];
    },
    getTotalNum() {
      let tableData = this.tableData;
      let num = tableData.reduce((total, item, index, arr) => {
        return total + item.quantity;
      }, 0);
      return num;
    },
    getTotalPrice() {
      let tableData = this.tableData;
      let totalprice = tableData.reduce((total, item, index, arr) => {
        return total + item.price * item.quantity;
      }, 0);
      return totalprice;
    }
  }
};
</script>

<style lang="scss">
@import "@/assets/css/settlementPage/index.scss";
</style>
